package com.exam.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.exam.pojo.domain.TrafficSign;
import com.exam.pojo.domain.TrafficSignCategory;
import com.exam.pojo.vo.SignVO;
import com.exam.pojo.vo.TrafficSignVO;
import com.exam.service.ITrafficSignService;
import com.exam.utils.CollUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class TrafficSignServiceImpl implements ITrafficSignService {

    private final MongoTemplate mongoTemplate;

    
    @Override
    public List<TrafficSignVO> list() {
        List<TrafficSign> list = mongoTemplate.findAll(TrafficSign.class);
        if(CollUtils.isNotEmpty(list)){
            Map<Long, List<TrafficSign>> map = list.stream().collect(Collectors.groupingBy(TrafficSign::getCategoryId));
            List<TrafficSignCategory> signCategories = mongoTemplate.findAll(TrafficSignCategory.class);
            Map<Object, TrafficSignCategory> cateMap = CollUtils.fieldValueMap(signCategories, "id");
            //组装数据
            List<TrafficSignVO> voList = new ArrayList<>(map.keySet().size());
            for (Long key : map.keySet()) {
                TrafficSignCategory category = cateMap.get(key);
                TrafficSignVO vo = BeanUtil.toBean(category, TrafficSignVO.class);
                vo.setSigns(BeanUtil.copyToList(map.get(key), SignVO.class));
                voList.add(vo);
            }
            //对集合进行排序
            voList = voList.stream().sorted(Comparator.comparing(TrafficSignVO::getRank)).collect(Collectors.toList());
            return voList;
        }
        return CollUtils.emptyList();
    }
}
